import { Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { DatabaseService } from '@/common/database';
import { IdService } from '@/common/snow-flake';
import { BusinessException } from '@/common/excepetion/business.exceptions';

@Injectable()
export class MenuService {
  constructor(
    private readonly db: DatabaseService,
    private readonly idService: IdService,
  ) {}

  /**
   * 根据用户id 查询菜单
   */
  async findAllListByUserId(userId: string) {
    let menus: CreateMenuDto[];
    let sql: string;

    // 管理员
    if (userId === '1') {
      sql = `select * from sys_menu where del_flag = '0'`;
      menus = await this.db.query<CreateMenuDto>(sql, []);
    } else {
      menus = [];
    }

    return menus;
  }

  /**
   * 添加菜单
   * @param menu
   * @returns
   */
  async addMenu(menu: CreateMenuDto, userId: string) {
    const sql = `insert into sys_menu(id, name, en_name, permission, path, parent_id, icon, visible, sort_order, keep_alive, embedded, menu_type, create_by, update_by) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    const id = this.idService.generateId();
    try {
      await this.db.query(sql, [
        id,
        menu.name,
        menu.enName,
        menu.permission,
        menu.path,
        menu.parentId,
        menu.icon,
        menu.visible,
        menu.sortOrder,
        menu.keepAlive,
        menu.embedded,
        menu.menuType,
        userId,
        userId,
      ]);
    } catch (error) {
      throw new BusinessException({ msg: '数据库插入异常' });
    }

    return menu;
  }
}
